/**
 * @author chenjuan
 * @time 2022-1-29 19:09 PM
 * @description 异步请求方法封装
 */
 import Axios from 'axios'
 import store from '../store'
 
 const Ajax = Axios.create({
     // timeout: 5000,
     baseURL: '/apis'
 })
 
 //拦截器，除了登录请求，其他请求都需要请求头中有token
 Ajax.interceptors.request.use(function(config) {
     //从store中获取token
     let token = store.getters['common/token']
     if(config.url !== '/user/login'){
         if(!!token){
             config.headers.token = token
             return config
         }else{
             return Promise.reject({code: 400, message: 'token不存在或已失效'})
         }
     }else{
         return config
     }
 })
 
 /**
  * 异步请求方法封装
  * @param {{url: String, method: 'GET' | 'POST' | 'DELETE' | 'PUT', data: any, params: any, timeout: number}} req 
  * @returns 
  */
 export default function(req) {
     //如果req没传或者不是一个对象，报错
     if(!req || req.constructor !== Object)    throw new Error('调用异步请求方法，参数必须为一个对象，且必传')
     if(!req.url) throw new Error('url为必传')
     return new Promise( resolve => {
         Ajax.request({
             url: req.url,
             method: req.method || 'GET',
             data: req.data || {},
             params: req.params || {},
             timeout: req.timeout || 2000,
             onUploadProgress: req.callback || (()=>{})
         }).then( ({data}) =>{
             resolve(data)
         }).catch(err => {
             resolve(err)
         })
     })
 }